package com.pactera.library.utils;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;

/**
 * 串口数据转换工具类
 * Created by Administrator on 2016/6/2.
 */
public class SerialDataUtils {
    //-------------------------------------------------------
    // 判断奇数或偶数，位运算，最后一位是1则为奇数，为0是偶数
    public static int isOdd(int num) {
        return num & 1;
    }

    //-------------------------------------------------------
    //Hex字符串转int 16进制转10进制
    public static int HexToInt(String inHex) {
        return Integer.parseInt(inHex, 16);
    }

    //-------------------------------------------------------
    //10进制转16进制
    public static String IntToHex(Integer strNumber) {
        return Integer.toHexString(strNumber);
    }

    //10进制转16进制
    public static String FloatToHex(Float strNumber) {
        return Float.toHexString(strNumber);
    }


    //-------------------------------------------------------
    //Hex字符串转byte
    public static byte HexToByte(String inHex) {
        return (byte) Integer.parseInt(inHex, 16);
    }

    //-------------------------------------------------------
    //1字节转2个Hex字符
    public static String Byte2Hex(Byte inByte) {
        return String.format("%02x", new Object[]{inByte}).toUpperCase();
    }

    //-------------------------------------------------------
    //字节数组转转hex字符串
    public static String ByteArrToHex(byte[] inBytArr) {
        StringBuilder strBuilder = new StringBuilder();
        for (byte valueOf : inBytArr) {
            strBuilder.append(Byte2Hex(Byte.valueOf(valueOf)));
            strBuilder.append(" ");
        }
        return strBuilder.toString();
    }

    //-------------------------------------------------------
    //字节数组转转hex字符串，可选长度
    public static String ByteArrToHex(byte[] inBytArr, int offset, int byteCount) {
        StringBuilder strBuilder = new StringBuilder();
        int j = byteCount;
        for (int i = offset; i < j; i++) {
            strBuilder.append(Byte2Hex(Byte.valueOf(inBytArr[i])));
        }
        return strBuilder.toString();
    }

    //-------------------------------------------------------
    //转hex字符串转字节数组
    public static byte[] HexToByteArr(String inHex) {
        byte[] result;
        int hexlen = inHex.length();
        if (isOdd(hexlen) == 1) {
            hexlen++;
            result = new byte[(hexlen / 2)];
            inHex = "0" + inHex;
        } else {
            result = new byte[(hexlen / 2)];
        }
        int j = 0;
        for (int i = 0; i < hexlen; i += 2) {
            result[j] = HexToByte(inHex.substring(i, i + 2));
            j++;
        }
        return result;
    }


    //10进制转16进制，一共4位，不足的用0补齐
    public static String IntToHexFillIn(Integer strNumber) {
        String strResult = Integer.toHexString(strNumber).toUpperCase();
        switch (strResult.length()) {
            case 1:
                strResult = "000" + strResult;
                break;
            case 2:
                strResult = "00" + strResult;
                break;
            case 3:
                strResult = "0" + strResult;
                break;
        }

        return strResult;
    }

    //10进制转16进制，一共2位，不足的用0补齐
    public static String IntToTwoHexFillIn(Integer strNumber) {
        String strResult = Integer.toHexString(strNumber).toUpperCase();
        switch (strResult.length()) {
            case 1:
                strResult = "0" + strResult;
                break;
        }

        return strResult;
    }


    //2个字节转换为16个位的二进制字符串
   /* public static String twoByteTo16BitsBinaryString(String str) {
        String s = byteTo8BitsString(HexToByte(str));
    }*/

    //一个字节转换为8个位的二进制字符串
    public static String byteTo8BitsString(byte b) {
        int z = b;
        z |= 256;
        String str = Integer.toBinaryString(z);
        //String str = Integer.toBinaryString(b);
        int len = str.length();
        //System.out.println("byte2bits len=" + len);
        return str.substring(len - 8, len);

    }


    //8个位的二进制字符串转换为一个字节
    public static byte bitsStringToByte(String bString) {
        byte result = 0;
        for (int i = bString.length() - 1, j = 0; i >= 0; i--, j++) {
            result += (Byte.parseByte(bString.charAt(i) + "") * Math.pow(2, j));
        }
        return result;

    }


    //汉字转化为16进制
    public static String chineseCharToHex(String str) {
        byte[] bytes;
        try {
            bytes = str.getBytes("gbk");
            return ByteArrToHex(bytes);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";

    }


    /**
     * 汉字转化为16进制，测试也可以，具体见 HexUtils.java 工具
     */
    public static String chineseCharToHex1(String data) {
        String hexString = "0123456789ABCDEF";
        byte[] bytes;
        try {
            bytes = data.getBytes("gbk");
            StringBuilder sb = new StringBuilder(bytes.length * 2);

            for (int i = 0; i < bytes.length; i++) {
                sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
                sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
            }
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";


    }

    /**
     * 在线转换网址：https://lostphp.com/hexconvert/
     * 将 4字节的16进制字符串，转换为32位带符号的十进制浮点型
     *
     * @param str 4字节 16进制字符
     * @return
     */
    public static float hexToFloat(String str) {
        return Float.intBitsToFloat(new BigInteger(str, 16).intValue());
    }
    /*public static String hexToFloat(String str) {
        return str;
    }*/

    /**
     * 10小数进制转16进制
     * 将带符号的32位浮点数装换为16进制
     *
     * @param value
     */
    public static String floatToHexString(Float value) {
        return Integer.toHexString(Float.floatToIntBits(value));
    }

   /* public static void main(String[] args) {
        String strHex = FloatToHex(1.5f);
        System.out.println("SerialDataUtils.main strHex=" + strHex);
        float fResult = hexToFloat("41a4c000");
        System.out.println("SerialDataUtils.main fResult=" + fResult);
    }*/

   /* public static void get_ttyS0_permissions() {
        try {
            Runtime.getRuntime().exec("adb shell");
            Runtime.getRuntime().exec("su");
            Runtime.getRuntime().exec("chmod 777 dev/ttyS0");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/
}
